package com.sumainfor.pc.epc.service.impl;

import com.sumainfor.common.Constants;
import com.sumainfor.common.exception.TCException;
import com.sumainfor.common.util.ContextUtils;
import com.sumainfor.common.util.CustomMap;
import com.sumainfor.common.util.JsonResult;
import com.sumainfor.common.utlis.ComUtils;
import com.sumainfor.common.utlis.HtmlUtil;
import com.sumainfor.common.utlis.ParamsCommon;
import com.sumainfor.pc.epc.dao.BuyerManageMapper;
import com.sumainfor.pc.epc.dao.SettlementManageMapper;
import com.sumainfor.pc.epc.feign.Zfeign.ZzuulFeign;
import com.sumainfor.pc.epc.service.BuyerAuditService;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.awt.*;
import java.math.BigDecimal;
import java.util.Map;

/**
 * @Author PuaChen
 * @Create 2018-12-24 10:52
 */
@Service
@Transactional(rollbackFor = Exception.class)
@Log4j2
public class BuyerAuditServiceImpl implements BuyerAuditService {

    @Autowired
    private BuyerManageMapper buyerManageMapper;

    @Autowired
    private BuyerManageServiceImpl buyerManageService;

    @Autowired
    private SettlementManageMapper settlementManageMapper;

    @Autowired
    private ComUtils comUtils;

    @Autowired
    private ZzuulFeign zullFign;

    /**
     * 备件采购单的审核接口
     * <p>
     * BuyId 备件采购单的主编号
     * State：4审核中（备件） 5被驳回（备件）
     * ErrorTitle：驳回类型
     * ErrorMessage： 驳回备注
     *
     * @param params
     * @return
     */
    @Override
    public JsonResult auditStockBuyer(Map<String, Object> params) {
        String buyerId = MapUtils.getString(params, "BuyId");
        Integer state = MapUtils.getInteger(params, "State");
        String title = MapUtils.getString(params, "ErrorTitle");
        String errorMessage = MapUtils.getString(params, "ErrorMessage");

        if (!state.equals(5) && !state.equals(2)) {
            return JsonResult.error("没有这个状态");
        }

        log.info("备件采购审核 ==> : {}", params);

        Map<String, Object> mainInfo = buyerManageMapper.getBuyerMainByBuyerId(buyerId);
        if (MapUtils.isEmpty(mainInfo)) {
            return JsonResult.error("没有这个采购单");
        }
        if (!MapUtils.getInteger(mainInfo, "BuyState").equals(4)) {
            return JsonResult.error("这个采购单已经审核过了");
        }

        int i = buyerManageMapper.updateBuyerMain(ParamsCommon.commonInsertParms(CustomMap.create()
                        .put("BuyId", buyerId)
                        .put("BuyState", state)
                        .put("ErrorTitle", title)
                        .put("ErrorMessage", errorMessage)
                , getClass()));

        if (i <= 0) {
            throw new TCException(JsonResult.actionFailure().getErrorMessage());
        }

        if (state.equals(2)) {
            //生成结算单 主表数据
            //计算总价格
            BigDecimal priceSum = buyerManageMapper.getBuyerInfoSumPriceForStock(buyerId);

            String staId = comUtils.getLocalTrmSeqNumByLook("Sta", Constants.DATA_SOURCE_TCEPC, "tcepc_statement", "StaId");
            i = settlementManageMapper.insertStaMain(ParamsCommon.commonInsertParms(CustomMap.create("StaId", staId)
                    .put("StaType", 0)
                    .put("StaCut", 2)
                    .put("SourceId", buyerId)
                    //已付金额
                    .put("PaidPrices", 0)
                    .put("CopeWithPrices", priceSum)
                    .put("UnpaidPrices", priceSum), getClass()));
            if (i <= 0) {
                throw new TCException("生成结算单失败");
            }
            //去生成结算单详表记录
            boolean success = buyerManageService.createStaInfo(buyerId);
            if (!success) {
                throw new TCException("生成结算单详表失败");
            }
        }

        if (state.equals(5)) {
            //被驳回
            CustomMap data = CustomMap.create("MeType", 7)
                    .put("Title", "被驳回的备件采购单")
                    .put("Content", HtmlUtil.stringToHTML("（" + buyerId + "）申请的备件采购单被驳回；", buyerId, Color.blue))
                    .put("by", ContextUtils.getUserId())
                    .put("IfJump", 1)
                    .put("Neturl", "/sys-engineeringmanager/buyer")
                    .put("term", 3);
            zullFign.AddMessage(data);
        }

        return JsonResult.actionSuccess();
    }


}
